package audio;

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JOptionPane;

public class WavePlayer extends Thread {

    private String filename;

    private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb

    public WavePlayer(String wavfile) {
	filename = wavfile;
    }

    @Override
    public void run() {

	File soundFile = new File(filename);
	if (!soundFile.exists()) {
	    System.err.println("Wave file not found: " + filename);
	    return;
	}

	AudioInputStream audioInputStream = null;
	try {
	    audioInputStream = AudioSystem.getAudioInputStream(soundFile);
	} catch (UnsupportedAudioFileException e1) {
	    e1.printStackTrace();
	    return;
	} catch (IOException e1) {
	    e1.printStackTrace();
	    return;
	}

	AudioFormat format = audioInputStream.getFormat();
	SourceDataLine auline = null;

	if (System.getProperty("os.name").equals("Linux") && System.getProperty("os.version").equals("3.0.0-16-generic")) {
	    try {
		Mixer.Info myMixer = null;
		for (Mixer.Info m : AudioSystem.getMixerInfo()) {
		    if (m.getName().equals("default [default]")) {
			myMixer = m;
			break;
		    }
		    JOptionPane.showMessageDialog(null, "No default playback line found.");
		}
		auline = AudioSystem.getSourceDataLine(format, myMixer);
		auline.open(format);
	    } catch (LineUnavailableException e) {
		e.printStackTrace();
	    }
	} else {
	    DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
	    try {
		auline = (SourceDataLine) AudioSystem.getLine(info);
		auline.open(format);
	    } catch (LineUnavailableException e) {
		e.printStackTrace();
		return;
	    } catch (Exception e) {
		e.printStackTrace();
		return;
	    }
	}
	

	auline.start();
	int nBytesRead = 0;
	byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];

	try {
	    while (nBytesRead != -1) {
		nBytesRead = audioInputStream.read(abData, 0, abData.length);
		if (nBytesRead >= 0)
		    auline.write(abData, 0, nBytesRead);
	    }
	} catch (IOException e) {
	    e.printStackTrace();
	    return;
	} finally {
	    auline.drain();
	    auline.close();
	}
    }
}